<?php

namespace App\Process;

use App\Utility\Cache;
use Carbon\Carbon;
use EasySwoole\Component\Process\AbstractProcess;

class UserLogin extends AbstractProcess{
    private $isRun = false;
    public function run($arg){
        //定时500ms检测有没有任务，有的话就while死循环执行
        $this->addTick(500,function (){
            if(!$this->isRun){
                $this->isRun = true;
                go(function (){
                    while (true){
                        try{
                            $queue = new Cache();
                            $task = $queue->onQueue($this->getProcessName())->read();
                            if($task){
                                $modelName =  'App\Model\Users'.ucfirst($task['name']).'Model';
                                $model = new $modelName;
                                $info = $model->where('openid',$task['openid'])->first();
                                if($info){
                                    //老用户，更新登陆时间
                                    $model->update(['id'=>$info['id'],'login_at'=>Carbon::now()]);
                                }else{
                                    //新用户，新增
                                    $model->create(['openid'=>$task['openid'],'reg_at'=>Carbon::now(),'login_at'=>Carbon::now()]);
                                }
                                unset($model);
                            }else{
                                break;
                            }
                            unset($queue);
                        }catch (\Throwable $throwable){
                            break;
                        }
                    }
                    $this->isRun = false;
                });
            }
        });
    }

    public function onShutDown()
    {
        // TODO: Implement onShutDown() method.
    }

    public function onReceive(string $str, ...$args)
    {
        // TODO: Implement onReceive() method.
    }
}
